<template>
  <div class="app-container">
    <el-drawer :title="title" :visible.sync="openDetail" size="80%" @close="cancel" :append-to-body="true">
      <template v-slot:title>
        <span class="titleDiv">{{ title }}</span>
      </template>
      <div style="padding: 0 20px">
        <el-tag size="large" style="font-size: 20px">基本信息</el-tag>
        <hr />
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="grid-content bg-purple">
              <span>领料单编号:</span>
              <span>{{ form.issueCode }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="grid-content bg-purple">
              <span>生产工单:</span>
              <span>{{ form.workorderCode }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="grid-content bg-purple">
              <span>领料日期:</span>
              <span>{{ form.issueDate }}</span>
            </div>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <div class="grid-content bg-purple">
              <span>仓库名称：</span>
              <span>{{ form.warehouseName }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="grid-content bg-purple">
              <span>单据状态:</span>
              <span>
                <dict-tag :options="dict.type.mes_order_status" :value="form.status" />
              </span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="grid-content bg-purple">
              <span>执行领出状态:</span>
              <span>{{
                form.leadStatus == "0" || !form.leadStatus ? "未领出" : "已领出"
              }}</span>
            </div>
          </el-col>
        </el-row>
        <el-tag size="large" style="font-size: 20px; margin-bottom: 10px; margin-top: 10px">物料列表</el-tag>
        <hr />
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-download" size="mini" @click="handlePrint">批量打印大条码</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-download" size="mini" @click="serialPrint">批量打印小条码</el-button>
          </el-col>
        </el-row>
        <el-table v-loading="loading" :data="routeproductbomList" :span-method="objectSpanMethod"
          @selection-change="handleSelectionChange" height="67vh">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="序号" align="center" width="50px" prop="issueCode">
            <template slot-scope="scope">
              <span>{{ scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column label="所属工序" align="center" prop="processName" />
          <el-table-column label="物料编号" align="center" prop="itemCode" />
          <el-table-column label="物料名称" align="center" prop="itemName" />
          <el-table-column label="规格型号" align="center" prop="specification" />

          <el-table-column label="单位" width="100" align="center" prop="unitOfMeasure" />
          <el-table-column label="用量:分子" width="80" align="center" prop="jdyNumerator" />
          <el-table-column label="用量:分母" align="center" prop="jdyDenominator" />
          <el-table-column label="领料仓库" width="100" align="center" prop="warehouseName" />
          <el-table-column label="应领数量" width="100" align="center" prop="payableQty" />
          <el-table-column label="领料数量" width="80" align="center" prop="quantityIssued" />
          <el-table-column label="未领数量" width="100" align="center" prop="unQuantityIssued" />
          <el-table-column label="批次号" width="80" align="center" prop="batchCode" />
          <el-table-column label="序列号" width="80" align="center" prop="sequenceCode">
            <template slot-scope="scope">
              <span v-if="!scope.row.sequenceCode || scope.row.sequenceCode.split(',').length < 2">{{
                scope.row.sequenceCode
              }}</span>
              <span v-else @click="handleViewSequenceCode(scope.row)" style="color: #1890ff;cursor: pointer;">查看</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" min-width="100">
            <template slot-scope="scope">
              <el-button size="mini" type="text" @click="handlePrint2(scope.row, '1')">大序列号打印</el-button>
              <el-button size="mini" type="text" @click="handlePrint2(scope.row, '2')">小序列号打印</el-button>
            </template>
          </el-table-column>
          <!-- <el-table-column label="领料日期" align="center" prop="issueDate" width="180" >
            <template slot-scope="scope">
              <span>{{
                parseTime(scope.row.issueDate, "{y}-{m}-{d} {h}:{m}:{s}")
              }}</span>
            </template>
          </el-table-column>-->
          <!-- <el-table-column label="单据状态" align="center" prop="status">
            <template slot-scope="scope">
              <dict-tag
                :options="dict.type.mes_order_status"
                :value="scope.row.status"
              />
            </template>
          </el-table-column>-->
        </el-table>
      </div>
    </el-drawer>
    <el-dialog title="提示" :visible.sync="dialogVisible" width="30%">
      <span>序列号：</span>
      <el-select v-model="multipleSerials" multiple placeholder="请选择">
        <el-option v-for="item in serialList" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSelectSerialList">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 查看序列号弹框 -->
    <el-dialog title="序列号" :visible.sync="sequenceCodeDialog" width="500px" append-to-body>
      <el-table :data="sequenceCodeList" style="max-height: 55vh;overflow: auto;">
        <el-table-column label="序号" type="index" align="center"></el-table-column>
        <el-table-column label="序列号" prop="value" align="center"></el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="sequenceCodeDialog = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listIssuedetail,
  printIssueLineSn,
  serialIssueLineSn,
} from "@/api/mes/wm/issueDetail";
export default {
  data() {
    return {
      serialPrintType: null,
      activeItemName: null,
      activeItemCode: null,
      selectWmIssueLineList: [],
      serialList: [],
      multipleSerials: null,
      dialogVisible: false,
      openDetail: false,
      title: "查看领料单",
      // 表单参数
      form: {},
      loading: false,
      routeproductbomList: [],
      issueId: null,
      // 选中数组
      ids: [],
      //物料编码
      itemCodes: [],
      measureCodes: [],
      //批量打印
      selectionList: [],
      // 展示序列号列表
      sequenceCodeDialog: false,
      sequenceCodeList: []
    };
  },
  dicts: ["mes_order_status"],
  methods: {
    //初始化函数
    init(row) {
      console.log(row, "子组件的row");
      this.form = row;
      //调接口需要的id
      this.workorderId = row.workorderId;
      this.issueId = row.issueId;
      this.openDetail = true;
      this.getList();
    },
    getList() {
      listIssuedetail({ issueId: this.issueId }).then((res) => {
        console.log(res, "详情table的res");
        if (res.code == 200) {
          this.routeproductbomList = res.data;
          this.getSpanArr(res.data || []);
        }
      });
    },
    // 取消按钮
    cancel() {
      this.openDetail = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        workorderId: null,
        workorderCode: null,
        workorderName: null,
        orderSource: null,
        sourceCode: null,
        productId: null,
        productCode: null,
        productName: null,
        productSpc: null,
        unitOfMeasure: null,
        quantity: null,
        quantityProduced: null,
        quantityChanged: null,
        quantityScheduled: null,
        clientId: null,
        clientCode: null,
        clientName: null,
        requestDate: null,
        parentId: null,
        status: 0,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        orderType: null,
        fPlanStartDate: null,
        fPlanFinishDate: null,
      };
      this.autoGenFlag = false;
      this.sequenceCodeDialog = false
      this.sequenceCodeList = []
      this.resetForm("form");
    },
    // 行合并
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 2) {
        const _row = this.spanArr[rowIndex]; // 合并行数
        const _col = this.spanArr[rowIndex] > 0 ? 1 : 0; // 合并的列数
        return {
          rowspan: _row,
          colspan: _col,
        };
      }
    },
    // 按照类型合并
    getSpanArr(data) {
      this.spanArr = []; // tip: 后台获取完成数据后，一定要重置spanArr=[],避免出现合并混乱！！！！！
      if (data.length > 0) {
        for (let i = 0; i < data.length; i++) {
          // 当为第一行时
          if (i === 0) {
            this.spanArr.push(1);
            this.pos = 0;
          } else {
            // 判断当前值是否与上一行的【名称】相等，相等则进行合并
            if (data[i].processName === data[i - 1].processName) {
              this.spanArr[this.pos] += 1; // 合并单元格：合并的行数 +1
              this.spanArr.push(0); // 0代表单元格是不需要显示, 已经被合并的单元格
            } else {
              this.spanArr.push(1); // 1代表当前这行的数据需要被显示
              this.pos = i;
            }
          }
        }
      }
    },
    //打印
    handlePrint(row) {
      let rowList = [];
      if (row.lineId) {
        rowList.push(row);
      }
      const WmIssueLineList =
        rowList.length != 0 ? rowList : this.selectionList;
      const itemCode = row.itemCode || this.itemCodes;
      console.log(WmIssueLineList, "WmIssueLineList");
      this.$modal
        .confirm('是否确认打印物料编号为"' + itemCode + '"的数据项？')
        .then(function () {
          return printIssueLineSn(WmIssueLineList);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("打印成功");
        })
        .catch(() => { });
    },
    handleSelectSerialList() {
      this.selectWmIssueLineList = this.activeItemCode;
      if (!this.multipleSerials.length) {
        this.$message.error("请先选择序列号");
        return;
      }
      const arr = this.multipleSerials.map((item) => {
        const obj = {
          itemCode: this.activeItemCode,
          itemName: this.activeItemName,
          sequenceCode: item,
        };
        return obj;
      });
      const that = this;
      this.$modal
        .confirm(
          '是否确认打印物料编号为"' + this.activeItemCode + '"的数据项？'
        )
        .then(function () {
          debugger;
          if (that.serialPrintType === "1") {
            return printIssueLineSn(arr);
          } else {
            return serialIssueLineSn(arr);
          }
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("打印成功");
        })
        .catch((err) => {
          console.log(err);
        });
    },
    handlePrint2(row, serialPrintType) {
      this.serialPrintType = serialPrintType;
      this.dialogVisible = true;
      this.multipleSerials = null;
      this.activeItemCode = row.itemCode;
      this.activeItemName = row.itemName;
      const arr = row.sequenceCode.split(",") || [];
      this.serialList = arr.map((res) => {
        const item = {
          label: res,
          value: res,
        };
        return item;
      });
    },
    //批量小序列号打印
    serialPrint(row) {
      let rowList = [];
      if (row.lineId) {
        rowList.push(row);
      }
      const WmIssueLineList =
        rowList.length != 0 ? rowList : this.selectionList;
      const itemCode = row.itemCode || this.itemCodes;
      this.$modal
        .confirm('是否确认打印物料编号为"' + itemCode + '"的数据项？')
        .then(function () {
          return serialIssueLineSn(WmIssueLineList);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("打印成功");
        })
        .catch(() => { });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      console.log(selection, "selection");
      this.selectionList = selection;
      this.itemCodes = selection.map((item) => item.itemCode);
    },
    handleViewSequenceCode(row) {
      this.sequenceCodeDialog = true
      this.sequenceCodeList = row.sequenceCode ? row.sequenceCode.split(',').map(item => ({ value: item })) : []
    }
  },
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.app-container ::v-deep .el-drawer__header {
  padding-top: 10px !important;
  padding-bottom: 5px !important;
  margin-bottom: 10px !important;
}

.bg-purple {
  display: flex;
  align-items: center;

  span:nth-child(1) {
    display: inline-block;
    // width: 100px;
    margin-right: 10px;
    white-space: nowrap;
    line-height: 30px;
  }
}

.titleDiv {
  font-weight: 700 !important;
  font-size: 20px;
}
</style>
